<script setup lang="ts">
import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRouterNavigation } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { h, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { getStock, getSupplierStock } from "../utils/common";
const { go } = useRouterNavigation();

// 组件
import { ImageViewer } from "@/components/common/ImageViewer";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { ChooseDepository } from "./components";

// icons
import arrowLeft from "@iconify-icons/ep/arrow-left";
import ShopCar from "@iconify-icons/ep/shopping-cart";

// api
import { addShopCart, getGoodsDetail } from "@/api/home/goods";
import { addStoreOrder } from "@/api/order/store";

// 富文本
import WangEditor from "@/components/common/WangEditor";

// 轮播图引入
import ThumbsSwiper from "@/components/common/ThumbsSwiper";

// 处理品牌列表
const specIndex = ref(0);
const buyForm = ref({
  depositoryType: 1,
  amount: 1
});

// 加入购物车
const doAddShopCar = () => {
  ElMessageBox.confirm("确认加入购物车?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    dangerouslyUseHTMLString: true,
    draggable: true
  }).then(async () => {
    let goodsSpec = goodsForm.value.goodsSpecList[specIndex.value];
    let finalPrice = dealDataRide(buyPrice.value);

    // 兑礼商品 发货仓默认仓库 如果是非预备货 赋值 供应商
    // depositoryType 发货仓 1 佳叽仓库  2：供应商仓
    // goodsType 商品类型 1抓机商品 2兑换礼品
    // preStockStatus 预备货 0否 1是
    let tempDepositoryType = buyForm.value.depositoryType;
    if (goodsForm.value.goodsType == 2) {
      tempDepositoryType = 1;
      let preStockStatus = goodsForm.value.preStockStatus || 0;
      if (preStockStatus === 0) {
        tempDepositoryType = 2;
      }
    }

    let parmas = {
      amount: buyForm.value.amount,
      depositoryType: tempDepositoryType,
      barCode: goodsSpec.barCode, // 	商品条码
      buyPrice: finalPrice, // 商品进价 单位分
      goodsCode: goodsForm.value.goodsCode, // 商品编码
      goodsId: goodsForm.value.id, // 商品id
      goodsName: goodsForm.value.goodsName, // 商品名称
      goodsType: goodsForm.value.goodsType, // 商品类型
      specCode: goodsSpec.specCode, // 规格编码
      specImageJson: goodsSpec.specImageJson || goodsForm.value.imageJson, // 规格图片json
      specName: goodsSpec.specName, // 规格名称
      storeId: useUserStoreHook().loginStoreId, // 门店id
      totalPrice: dealDataRide(buyForm.value.amount, finalPrice)
    };
    await addShopCart(parmas);
    message("添加成功", { type: "success" });
    sessionStorage.setItem("isHaveAddGoods", "1");
    go(-1);
  });
};

// 选择到货仓库
const chooseDepoRef = ref();
const doChooseDepo = () => {
  addDialog({
    title: "选择仓库",
    props: {
      goodsColumns: []
    },
    width: "500px",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(ChooseDepository, { ref: chooseDepoRef }),
    beforeSure: async (done, { closeLoading }) => {
      const FormRef = chooseDepoRef.value.getRef();
      FormRef.validate(async valid => {
        if (valid) {
          let submitForm = chooseDepoRef.value.getForm();
          doOrder(submitForm, done);
        }
        closeLoading();
      });
    },
    beforeCancel: done => {
      done();
    }
  });
};

// 直接下单
const doOrder = (submitForm, done) => {
  let msg = `确认直接下单到仓库: <span class='text-orange-500'>'${submitForm.depositoryName}'</span> ?`;
  ElMessageBox.confirm(msg, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    dangerouslyUseHTMLString: true,
    draggable: true
  }).then(async () => {
    let goodsSpec = goodsForm.value.goodsSpecList[specIndex.value];
    let finalPrice = dealDataRide(buyPrice.value);

    // 兑礼商品 发货仓默认仓库 如果是非预备货 赋值 供应商
    // depositoryType 发货仓 1 佳叽仓库  2：供应商仓
    // goodsType 商品类型 1抓机商品 2兑换礼品
    // preStockStatus 预备货 0否 1是
    let tempDepositoryType = buyForm.value.depositoryType;
    if (goodsForm.value.goodsType == 2) {
      tempDepositoryType = 1;
      let preStockStatus = goodsForm.value.preStockStatus || 0;
      if (preStockStatus === 0) {
        tempDepositoryType = 2;
      }
    }

    let parmas = {
      orderMethod: 1,
      depositoryId: submitForm.depositoryId,
      depositoryName: submitForm.depositoryName,
      goodsIds: [goodsForm.value.id],
      des: submitForm.des,
      storeId: useUserStoreHook().loginStoreId, // 门店id
      storeOrderShoppingCartAddRequest: {
        amount: buyForm.value.amount,
        depositoryType: tempDepositoryType,
        barCode: goodsSpec.barCode, // 	商品条码
        buyPrice: finalPrice, // 商品进价 单位分
        goodsCode: goodsForm.value.goodsCode, // 商品编码
        goodsId: goodsForm.value.id, // 商品id
        goodsName: goodsForm.value.goodsName, // 商品名称
        goodsType: goodsForm.value.goodsType, // 商品类型
        specCode: goodsSpec.specCode, // 规格编码
        specImageJson: goodsSpec.specImageJson || goodsForm.value.imageJson, // 规格图片json
        specName: goodsSpec.specName, // 规格名称
        totalPrice: dealDataRide(buyForm.value.amount, finalPrice)
      }
    };
    await addStoreOrder(parmas);
    message("下单成功", { type: "success" });
    done();
    go(-1);
  });
};

const typeChange = type => {
  getBuyPrice();
};

// 获取商品价格
const getBuyPrice = () => {
  // 1: 佳叽仓库 2:供应商仓
  let price = 0;
  let goodsSpec = goodsForm.value.goodsSpecList[specIndex.value];
  let depoType = buyForm.value.depositoryType;
  if (
    depoType == 1 &&
    goodsSpec.stockItemList &&
    goodsSpec.stockItemList.length > 0
  ) {
    // 获取库存成本均价
    price = dealDataExcept(goodsSpec.stockItemList[0].avgBuyPrice) || 0;
  } else {
    // 获取门店进价
    if (goodsSpec && goodsSpec.brandRel) {
      price = dealDataExcept(goodsSpec.brandRel.storeBuyPrice) || 0;
    }
  }
  buyPrice.value = price;
};

// 页面加载
const buyPrice = ref(0);
const goodsForm = ref<any>({});
const loading = ref(false);
onMounted(async () => {
  const { query } = useRoute();
  if (query.id) {
    loading.value = true;

    let { data } = await getGoodsDetail(query.id);
    data.recommendIndex = dealDataExcept(data.recommendIndex, 10) || 0;
    buyForm.value.amount = data.orderMin || 1;

    // 判断是否展示库存信息
    let isShowKcxx = false;
    let goodsSpecList = data.goodsSpecList || [];
    if (goodsSpecList.length > 0) {
      isShowKcxx = true;
      // 捉机商品单规格不展示
      if (data.goodsType == 1 && goodsSpecList.length == 1) {
        isShowKcxx = false;
      }
    }
    data.isShowKcxx = isShowKcxx;

    goodsForm.value = data;
    if (!goodsForm.value.depositoryStockAuth) {
      buyForm.value.depositoryType = 2;
    }
    getBuyPrice();
    loading.value = false;
  }
});

defineOptions({
  name: "GoodsDetail"
});
</script>

<template>
  <div v-loading="loading" class="goods-detail">
    <el-card class="w-full mb-[10px]" shadow="always">
      <div
        class="flex items-center cursor-pointer font-bold"
        @click.stop="go(-1)"
      >
        <IconifyIconOffline :icon="arrowLeft" class="mr-2" />
        <div>商品信息</div>
      </div>
      <div class="flex pt-[10px] pl-[10px]">
        <!-- 缩率轮播图 -->
        <div class="w-[500px] h-[405px] mr-[30px]">
          <ThumbsSwiper :file="goodsForm.imageJson" />
        </div>
        <!-- 商品信息 -->
        <div class="flex-1">
          <div class="mb-[10px] text-black font-bold">
            {{ goodsForm.goodsName || "--" }}
            <el-tag
              v-if="goodsForm.hasBuy"
              class="ml-1"
              type="success"
              size="small"
            >
              已购
            </el-tag>
          </div>
          <el-form ref="formRef" :model="goodsForm" label-width="76px">
            <el-form-item label="商品编码:" class="flex-1">
              <div>{{ goodsForm.goodsCode || "--" }}</div>
            </el-form-item>
            <el-form-item label="商品类目:" class="flex-1">
              <div>{{ goodsForm.categoryName || "--" }}</div>
            </el-form-item>
            <el-form-item label="商品类型:" class="flex-1">
              <DictTag
                dict-type="PRODUCT_TYPE"
                :dict-value="goodsForm.goodsType"
              />
            </el-form-item>
            <el-form-item
              v-if="goodsForm.orderMin"
              label="起订量:"
              class="flex-1"
            >
              <div>{{ goodsForm.orderMin || "--" }}</div>
            </el-form-item>
            <!-- 兑换礼品展示 -->
            <template v-if="goodsForm.goodsType == 2">
              <el-form-item label="计量单位:" class="flex-1">
                <div>{{ goodsForm.unitItemName || "--" }}</div>
              </el-form-item>
              <el-form-item label="陈列建议:">
                <div>{{ goodsForm.advise || "--" }}</div>
              </el-form-item>
              <el-form-item label="陈列推荐:">
                <ImageViewer
                  :src="goodsForm.recommendImageJson"
                  radius="8px"
                  show-count="10"
              /></el-form-item>
            </template>

            <el-form-item label="推荐指数:">
              <div>
                <el-rate v-model="goodsForm.recommendIndex" disabled />
              </div>
            </el-form-item>
            <el-form-item v-if="goodsForm.isShowKcxx" label="库存信息:">
              <div class="kcxx">
                <div class="flex">
                  <div class="w-[150px]">规格</div>
                  <div class="flex-1">仓库库存</div>
                  <div class="flex-1">供应商库存</div>
                </div>
                <div
                  v-for="(item, index) in goodsForm.goodsSpecList"
                  :key="index"
                  class="flex"
                >
                  <div class="w-[150px]">{{ item.specName || "主规格" }}</div>
                  <div class="flex-1">{{ getStock(item.stockItemList) }}</div>
                  <div class="flex-1">
                    {{ getSupplierStock(item.stockSupplierList) }}
                  </div>
                </div>
              </div>
            </el-form-item>
            <!-- 商品规格 -->
            <el-divider />
            <el-form-item
              v-if="
                goodsForm.goodsSpecList && goodsForm.goodsSpecList.length > 1
              "
              label="商品规格:"
            >
              <div class="specs">
                <div
                  v-for="(item, index) in goodsForm.goodsSpecList"
                  :key="index"
                  class="spec"
                  :class="{ act: specIndex == index }"
                  @click="
                    specIndex = index;
                    getBuyPrice();
                  "
                >
                  <ImageViewer
                    :src="item.specImageJson || goodsForm.imageJson"
                    radius="50%"
                  />
                  <div class="ml-[8px]">{{ item.specName || "主规格" }}</div>
                </div>
              </div>
            </el-form-item>
            <!--  兑换礼品不展示 -->
            <el-form-item v-if="goodsForm.goodsType == 1" label="发货仓:">
              <el-radio-group
                v-model="buyForm.depositoryType"
                @change="typeChange"
              >
                <el-radio :value="1" :disabled="!goodsForm.depositoryStockAuth">
                  佳叽仓库
                </el-radio>
                <el-radio :value="2">供应商仓</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="">
              <div class="goods-opt">
                <div class="price-box">
                  ¥
                  <span class="price">{{ buyPrice }}</span>
                </div>
                <el-input-number
                  v-model="buyForm.amount"
                  :precision="0"
                  :min="goodsForm.orderMin || 1"
                  :max="10000"
                />
                <div class="btn">
                  <div class="shop-car" @click="doAddShopCar">
                    <IconifyIconOffline class="text-white" :icon="ShopCar" />
                  </div>
                  <div class="do-order" @click="doChooseDepo">直接下单</div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!--  兑换运费规则 、商品详情 -->
    <div class="flex">
      <el-card class="w-full" shadow="always">
        <div class="card-title">商品详情</div>
        <div class="html-box">
          <WangEditor
            v-if="
              goodsForm.goodsDetail && goodsForm.goodsDetail != '<p><br></p>'
            "
            v-model="goodsForm.goodsDetail"
            disable
          />
          <el-empty v-else description="无商品详情~" />
        </div>
      </el-card>
    </div>
  </div>
</template>
<style lang="scss" scoped>
:deep(.bd-hide .el-table--fit .el-table__inner-wrapper:before) {
  background-color: #fff;
}
:deep(.icon-no .el-table__expand-icon) {
  display: none;
}
:deep(.el-card__body) {
  padding: 15px;
}
.goods-detail {
  min-width: 1000px;
}
.el-form-item {
  margin-bottom: 5px;
}
.card-title {
  font-weight: bold;
  margin-bottom: 10px;
}
.spec-box {
  .spec-item {
    padding: 10px;
    border: 1px solid #efefef;
    border-radius: 5px;
    margin-bottom: 20px;
  }
}
.html-box {
  min-height: 400px;
  border: 1px solid #efefef;
  border-radius: 5px;
  padding: 10px;
  img {
    max-width: 100%;
  }
}
.kcxx {
  width: 380px;
  padding: 10px;
  line-height: 25px;
  border-radius: 5px;
  background-color: #e5e5da;
  text-align: center;
}
.specs {
  display: flex;
  .spec {
    padding: 15px 20px;
    margin: 0 15px 15px 0;
    border-radius: 8px;
    border: 1px solid #efefef;
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .spec.act {
    border: 1px solid #409eff;
  }
}
.goods-opt {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 10px;
  .price-box {
    color: red;
    font-size: 20px;
    min-width: 120px;
    .price {
      font-size: 30px;
    }
  }
  .btn {
    font-size: 14px;
    color: #fff;
    width: 120px;
    height: 35px;
    line-height: 35px;
    display: flex;
    border-radius: 15px;
    overflow: hidden;
    cursor: pointer;
    margin-left: 15px;
    .shop-car {
      font-size: 20px;
      width: 40px;
      height: 100%;
      background-color: orange;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .do-order {
      font-size: 15px;
      flex: 1;
      text-align: center;
      background-color: red;
      &.disable {
        opacity: 0.8;
        background-color: #999;
      }
    }
  }
}
</style>
